﻿package net.wangit.framework.config;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.wangit.Path;
import net.wangit.framework.exception.ConfigurationException;
import net.wangit.util.FileUtil;
import net.wangit.util.XMLUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;

public class GlobalSettings {

	private static final Log log = LogFactory
			.getLog(net.wangit.framework.config.GlobalSettings.class);
	private static String contextRoot;
	private static Map domains;
	private static boolean GZIPEnabled;
	private static String cacheProvider;
	private static String language;
	private static String country;
	private static String encoding;

	public GlobalSettings() {
	}

	public static void load() {
		String path = Path.getHomePath() + "/global.xml";
		domains = new HashMap();
		try {
			if (!FileUtil.exists(path)) {
				log.error((new StringBuilder("global file not found:")).append(
						path).toString());
				throw new ConfigurationException("global file not found!");
			}
			Document document = XMLUtil.parseByPath(path);
			Element root = document.getRootElement();
			contextRoot = XMLUtil.getTextString(root, "root", "app");
			Element domainsNode = root.element("domains");
			List domainList = domainsNode.elements("domain");
			if (domainList != null) {
				for (int i = 0; i < domainList.size(); i++)
					domains.put(((Element) domainList.get(i)).getText(), null);

			}
			GZIPEnabled = XMLUtil.getTextBoolean(root, "gzip-enabled", true);
			cacheProvider = XMLUtil.getTextString(root, "cache-provider",
					"mapcache");
			Element i18n = root.element("i18n");
			language = XMLUtil.getTextString(i18n, "language", "zh");
			country = XMLUtil.getTextString(i18n, "country", "CN");
			encoding = XMLUtil.getTextString(i18n, "encoding", "UTF-8");
		} catch (Exception e) {
			log.error("load global settings failed!");
			throw new ConfigurationException(path, e);
		}
		log.info("load global settings successfully.");
	}

	public static boolean isGZIPEnabled() {
		return GZIPEnabled;
	}

	public static String getCacheProvider() {
		return cacheProvider;
	}

	public static String getCountry() {
		return country;
	}

	public static String getEncoding() {
		return encoding;
	}

	public static String getLanguage() {
		return language;
	}

	public static boolean isAccessibleDomain(String domain) {
		return domains.containsKey(domain);
	}

	public static String getContextRoot() {
		return contextRoot;
	}

}
